package com.aizuda.boot.modules.business.contract.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.aizuda.boot.modules.business.contract.dto.UserInfo;
import com.aizuda.boot.modules.system.entity.SysRole;
import com.aizuda.boot.modules.system.entity.vo.LoginUserVo;
import com.aizuda.boot.modules.system.service.ISysRoleService;
import com.aizuda.boot.modules.system.service.ISysUserRoleService;
import com.aizuda.boot.modules.system.service.ISysUserService;
import com.aizuda.service.spring.SpringHelper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hjw
 * @description
 * @date 2025年06月23日 11:13
 */
public class AuthUtil {
    public static final String FEISHU_TENANT_KEY = "feiShuTenantKey";

    public static final String ADMIN = "admin";

    /**
     * 获取当前登录用户
     *
     * @return
     */
    public static UserInfo getCurrentUser() {

        ISysUserService sysUserService = SpringUtil.getBean(ISysUserService.class);
        LoginUserVo userInfo = sysUserService.getUserInfo();

        // 获取当前用户信息
        //UserInfo userInfo = new UserInfo();
        //BeanUtil.copyProperties(sysUser, userInfo);
        //userInfo.setSysTenantKey(tenantKey);
        //userInfo.setFeiShuTenantKey((String) ssoToken.getData().get(FEISHU_TENANT_KEY));
        return userInfo;
    }

    /**
     * 当前登录用户是否为超级管理员
     */
    public static boolean isSuperAdmin() {
        UserInfo currentUser = getCurrentUser();
        if (currentUser == null) {
            return false;
        }
        // 用户名为 admin 直接返回 true
        if (ADMIN.equals(currentUser.getUsername())) {
            return true;
        }
        // 判断是否拥有 admin 角色
        Long userId = currentUser.getEmployeeId();
        if (userId == null) {
            return false;
        }
        ISysUserRoleService sysUserRoleService = SpringHelper.getBean(ISysUserRoleService.class);
        List<Long> roleIds = sysUserRoleService.listRoleIdsByUserId(userId);
        if (CollUtil.isEmpty(roleIds)) {
            return false;
        }
        ISysRoleService sysRoleService = SpringHelper.getBean(ISysRoleService.class);
        return sysRoleService.count(
                Wrappers.<SysRole>lambdaQuery()
                        .in(SysRole::getId, roleIds)
                        .eq(SysRole::getAlias, ADMIN)
        ) > 0;
    }

    /**
     * 判断当前用户是否有指定租户的权限
     *
     * @param targetTenantKey 目标租户key
     * @return 是否有权限
     */
    public static boolean hasTenantPermission(String targetTenantKey) {
        if (targetTenantKey == null) {
            return false;
        }

        // 超级管理员有所有权限
//        if (isSuperAdmin()) {
//            return true;
//        }

        UserInfo currentUser = getCurrentUser();
        if (currentUser == null) {
            return false;
        }

        // 检查用户的租户列表中是否包含目标租户
        if (currentUser instanceof LoginUserVo) {
            LoginUserVo loginUserVo = (LoginUserVo) currentUser;
            if (loginUserVo.getSysTenantList() != null) {
                return loginUserVo.getSysTenantList().stream()
                        .anyMatch(tenant -> targetTenantKey.equals(tenant.getTenantKey()));
            }
        }

        // 兼容旧的方式，检查当前租户
        return targetTenantKey.equals(currentUser.getSysTenantKey());
    }

    /**
     * 获取当前用户的所有租户key列表
     *
     * @return 租户key列表
     */
    public static List<String> getUserTenantKeys() {
        UserInfo currentUser = getCurrentUser();
        if (currentUser == null) {
            return List.of();
        }

        // 超级管理员不限制租户
//        if (isSuperAdmin()) {
//            return null; // null 表示不限制
//        }

        if (currentUser instanceof LoginUserVo) {
            LoginUserVo loginUserVo = (LoginUserVo) currentUser;
            if (loginUserVo.getSysTenantList() != null && !loginUserVo.getSysTenantList().isEmpty()) {
                return loginUserVo.getSysTenantList().stream()
                        .map(tenant -> tenant.getTenantKey())
                        .filter(key -> key != null)
                        .distinct()
                        .collect(Collectors.toList());
            }
        }

        // 兼容旧的方式，只返回当前租户
        if (currentUser.getSysTenantKey() != null) {
            return List.of(currentUser.getSysTenantKey());
        }

        return List.of();
    }

}
